import random
import string

from django.conf import settings
from cryptography.fernet import Fernet

ENCRYPTION_KEY = settings.ENCRYPTION_KEY or Fernet.generate_key()
fernet = Fernet(ENCRYPTION_KEY)


def generate_password(length=16):
    """生成密码"""
    if length < 8:
        length = 8

    # 确保每种字符至少包含一个
    password = [
        random.choice(string.ascii_lowercase),
        random.choice(string.ascii_uppercase),
        random.choice(string.digits),
    ]

    all_chars = string.ascii_letters + string.digits
    password += [random.choice(all_chars) for _ in range(length - 4)]
    random.shuffle(password)

    return ''.join(password)


def encrypt_password(password):
    """加密密码"""
    return fernet.encrypt(password.encode('utf-8')).decode('utf-8')


def decrypt_password(encrypted_password):
    """解密密码"""
    return fernet.decrypt(encrypted_password.encode('utf-8')).decode('utf-8')
